package com.conversationboard.model.banrequests;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.conversationboard.cache.banvote.BanVoteCache;
import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

public class BanRequests {

	public static boolean hasAlreadyRequestedBan(String bannerLoginId, String toBeBannedLoginId) throws SQLException {

		/* First check the cache */

		if (BanVoteCache.hasVotedForBanAlready(bannerLoginId, toBeBannedLoginId)) {
			return true;
		}

		/* If not in the cache, check the database and add into the cache if found */

		Connection connection = null;

		try {
			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.GET_BAN_REQUESTS_FOR_USER);
			statement.setString(1, bannerLoginId);

			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			boolean found = false;

			while (resultSet.next()) {
				String loginId = resultSet.getString("banloginid");

				if (loginId.equalsIgnoreCase(toBeBannedLoginId)) {
					found = true;
					break;
				}
			}

			statement.close();

			if (found) {
				return true;
			}

			return false;

		} finally {
			Database.close(connection);
		}
	}


	/**
	 * Add one to the user's ban counter, as held on the userroles table.
	 * 
	 * @param toBeBannedLoginId
	 * @throws SQLException
	 */

	public static void addBanRequest(String loginId, String ipAddress, String toBeBannedLoginId, int boardId, int threadId, int messageId, String body) throws SQLException {

		Connection connection = null;

		try {

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.RECORD_BAN_REQUEST);
			statement.setString(1, loginId);
			statement.setString(2, ipAddress);
			statement.setString(3, toBeBannedLoginId);
			statement.setInt(4, boardId);
			statement.setInt(5, threadId);
			statement.setInt(6, messageId);
			statement.setString(7, body);

			statement.executeUpdate();

			statement.close();

		} finally {
			Database.close(connection);
		}
	}

}
